package com.example.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SendRequest {

    public static void main(String[] args) throws Exception {

        //用线程池发送请求
        ExecutorService executor = Executors.newFixedThreadPool(1000);

        //发送请求
        while (true) {
            for (int i = 0; i < 100; i++) {
                int finalI = i;
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        String result = null;
                        try {
                            result = getRequest("http://localhost/");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println("现在请求 " + finalI + " 结果是：" );
                    }
                });
            }
            Thread.sleep(1000);
        }

        //等待线程执行完毕，每一个task都发送了请求并获取结果解析后放到task中的某个变量中，执行完后就可以获得这些变量来获得所要的结果
//        executor.shutdown();
//        while (!executor.isTerminated()) {
//            System.out.println("线程关闭");
//        }
    }

    /**
     * @param url：http接口地址
     * @param param：传入参数，格式为?param1=xxx&param2=xxx，如果值xxx含有特殊字符，可以用param = "image=" + URLEncoder.encode(image,"utf-8");
     * @throws Exception
     * @return: 返回调用接口得到的json字符串（是否为json字符串决定于http接口），是json字符串则可以进行相应解析，Map<String,Object> moodRes = (Map<String,Object>)JSONObject.parse(result)
     */
    public static String postRequest(String url, String param) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String getRequest(String url) throws Exception {
        String message = "";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

            http.connect();

            InputStream is = http.getInputStream();
            int size = is.available();

            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }
}
